var api = require('../../utils/api.js')
var app = getApp()
var Ajax = require("../../utils/ajax.js")
var Modal = require("../../utils/modal.js")
Page({
  data: {
    groups:[],
    showchoose:false
  },
  choose(e){
    var index = e.currentTarget.dataset.index;
    var temp_str_choosen = 'groups[' + index + '].choosen';
    if (this.data.groups[index].choosen) {
      this.setData({ [temp_str_choosen]: false });
    } else {
      this.setData({ [temp_str_choosen]: true });
    }
  },
  tochoose(){
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2];
    var newgroups = prevPage.data.groups;
    var oldgroups = this.data.groups;
    for (var i = 0; i < newgroups.length; i++)
      newgroups[i].choosen = false;
    for (var i = 0; i < newgroups.length; i++){
      for (var j = 0; j < oldgroups.length; j++) {
        if (newgroups[i].id == oldgroups[j].id) {
          newgroups[i].choosen = true;
          oldgroups.splice(j, 1);
          break;
        }
      }
    }
    this.setData({
      showchoose: true,
      groups: newgroups
    })
  },
  cancel() {
    this.setData({ showchoose: false})
  },
  reset(){
    var groups= this.data.groups;
    var groupaddrlist =[];
    var groupidlist = [];
    for(var i=0;i<groups.length&&groups[i].choosen;i++){
      groupaddrlist.push(groups[i].groupaddress);
      groupidlist.push(groups[i].id);
    }
    var mesh = app.globalData.activemesh;
    Modal.load("配置中");
    mesh.remoteConfig(app.globalData.activecon.address, groupaddrlist,(res)=>{
      Modal.loadfinish();
      if(res.code ==0){
        Ajax.AsyncPost("/con/config_con/",{ c_id: app.globalData.activecon.c_id, groupidlist: groupidlist },(data) => {
            Modal.showSuc("配置成功！")
            wx.navigateBack();
        })
      }
    })
  },
  onShow() {
    Ajax.AsyncPost("/con/get_group_of_con/",{ c_id: app.globalData.activecon.c_id },(data) => {
        this.setData({groups: data.groups});
    })
  },
  onLoad() {
    this.setData({
      phoneheight: app.globalData.phoneheight,
      fix_position: app.globalData.fix_position,
      phonewidth: app.globalData.phonewidth,
      rpxRatio: app.globalData.phonewidth / 750
    })
  }
})